<template>
  <div class="coupon-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑优惠券' : '创建优惠券' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="coupon-form"
      >
        <!-- 基本信息 -->
        <el-divider>基本信息</el-divider>
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>

        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="discount">折扣券</el-radio>
            <el-radio label="amount">满减券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          :label="form.type === 'discount' ? '折扣率' : '优惠金额'"
          prop="value"
        >
          <template v-if="form.type === 'discount'">
            <el-input-number
              v-model="form.value"
              :min="0"
              :max="10"
              :precision="1"
              :step="0.1"
              placeholder="请输入折扣率"
            />
            <span class="form-tip">折</span>
          </template>
          <template v-else>
            <el-input-number
              v-model="form.value"
              :min="0"
              :precision="2"
              :step="1"
              placeholder="请输入优惠金额"
            />
            <span class="form-tip">元</span>
          </template>
        </el-form-item>

        <el-form-item label="使用门槛" prop="minAmount">
          <el-input-number
            v-model="form.minAmount"
            :min="0"
            :precision="2"
            :step="1"
            placeholder="请输入使用门槛"
          />
          <span class="form-tip">元（0表示无门槛）</span>
        </el-form-item>

        <el-form-item label="有效期" prop="validityType">
          <el-radio-group v-model="form.validityType">
            <el-radio label="fixed">固定时间</el-radio>
            <el-radio label="dynamic">领取后生效</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="form.validityType === 'fixed'">
          <el-form-item label="生效时间" prop="timeRange">
            <el-date-picker
              v-model="form.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
            />
          </el-form-item>
        </template>

        <template v-else>
          <el-form-item label="生效天数" prop="validDays">
            <el-input-number
              v-model="form.validDays"
              :min="1"
              :max="365"
              placeholder="请输入生效天数"
            />
            <span class="form-tip">天</span>
          </el-form-item>
        </template>

        <!-- 使用规则 -->
        <el-divider>使用规则</el-divider>
        <el-form-item label="使用说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入使用说明"
          />
        </el-form-item>

        <el-form-item label="每人限领" prop="perLimit">
          <el-input-number
            v-model="form.perLimit"
            :min="1"
            :max="999"
            placeholder="请输入每人限领数量"
          />
          <span class="form-tip">张</span>
        </el-form-item>

        <el-form-item label="使用范围" prop="scope">
          <el-radio-group v-model="form.scope">
            <el-radio label="all">全场通用</el-radio>
            <el-radio label="category">指定分类</el-radio>
            <el-radio label="product">指定商品</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="form.scope === 'category'">
          <el-form-item label="选择分类" prop="categoryIds">
            <el-cascader
              v-model="form.categoryIds"
              :options="categoryOptions"
              :props="{
                checkStrictly: true,
                multiple: true,
                value: 'id',
                label: 'name'
              }"
              placeholder="请选择商品分类"
              clearable
            />
          </el-form-item>
        </template>

        <template v-if="form.scope === 'product'">
          <el-form-item label="选择商品" prop="productIds">
            <div class="product-selection">
              <el-button type="primary" @click="handleSelectProducts">
                选择商品
              </el-button>
              <el-table
                v-if="form.products.length > 0"
                :data="form.products"
                border
                style="width: 100%; margin-top: 20px"
              >
                <el-table-column prop="name" label="商品名称" min-width="200" />
                <el-table-column prop="price" label="商品价格" width="120">
                  <template #default="{ row }">
                    ¥{{ row.price }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      link
                      @click="handleRemoveProduct($index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </template>

        <!-- 发放规则 -->
        <el-divider>发放规则</el-divider>
        <el-form-item label="发放总量" prop="totalQuantity">
          <el-input-number
            v-model="form.totalQuantity"
            :min="1"
            :max="999999"
            placeholder="请输入发放总量"
          />
          <span class="form-tip">张</span>
        </el-form-item>

        <el-form-item label="发放方式" prop="issueType">
          <el-radio-group v-model="form.issueType">
            <el-radio label="auto">自动发放</el-radio>
            <el-radio label="manual">手动发放</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="form.issueType === 'auto'">
          <el-form-item label="发放条件" prop="issueCondition">
            <el-radio-group v-model="form.issueCondition">
              <el-radio label="register">新用户注册</el-radio>
              <el-radio label="first_order">首单购买</el-radio>
              <el-radio label="level">会员等级</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="form.issueCondition === 'level'"
            label="会员等级"
            prop="levelIds"
          >
            <el-select
              v-model="form.levelIds"
              multiple
              placeholder="请选择会员等级"
            >
              <el-option
                v-for="level in memberLevels"
                :key="level.id"
                :label="level.name"
                :value="level.id"
              />
            </el-select>
          </el-form-item>
        </template>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品选择对话框 -->
    <el-dialog
      v-model="productDialog.visible"
      title="选择商品"
      width="800px"
      append-to-body
    >
      <div class="product-dialog-content">
        <div class="search-bar">
          <el-input
            v-model="productDialog.keyword"
            placeholder="请输入商品名称搜索"
            clearable
            @keyup.enter="handleSearchProducts"
          >
            <template #append>
              <el-button @click="handleSearchProducts">搜索</el-button>
            </template>
          </el-input>
        </div>

        <el-table
          :data="productDialog.list"
          border
          style="width: 100%"
          @selection-change="handleProductSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="商品名称" min-width="200" />
          <el-table-column prop="price" label="商品价格" width="120">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100" />
          <el-table-column prop="sales" label="销量" width="100" />
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="productDialog.page.current"
            v-model:page-size="productDialog.page.size"
            :total="productDialog.page.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleProductPageSizeChange"
            @current-change="handleProductPageChange"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="productDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmProducts">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import {
  getMerchantCouponDetail,
  createMerchantCoupon,
  updateMerchantCoupon,
  getMerchantProducts,
  getMerchantCategories,
  getMerchantMemberLevels
} from '@/api/merchant'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive({
  name: '',
  type: 'amount',
  value: 0,
  minAmount: 0,
  validityType: 'fixed',
  timeRange: [],
  validDays: 7,
  description: '',
  perLimit: 1,
  scope: 'all',
  categoryIds: [],
  productIds: [],
  products: [],
  totalQuantity: 1000,
  issueType: 'manual',
  issueCondition: 'register',
  levelIds: []
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入优惠值', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (form.type === 'discount' && (value < 0 || value > 10)) {
          callback(new Error('折扣率必须在 0-10 之间'))
        } else if (form.type === 'amount' && value <= 0) {
          callback(new Error('优惠金额必须大于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  minAmount: [
    { required: true, message: '请输入使用门槛', trigger: 'blur' }
  ],
  validityType: [
    { required: true, message: '请选择有效期类型', trigger: 'change' }
  ],
  timeRange: [
    {
      required: true,
      message: '请选择生效时间',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.validityType === 'fixed' && (!value || value.length !== 2)) {
          callback(new Error('请选择生效时间'))
        } else {
          callback()
        }
      }
    }
  ],
  validDays: [
    {
      required: true,
      message: '请输入生效天数',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.validityType === 'dynamic' && (!value || value < 1)) {
          callback(new Error('请输入生效天数'))
        } else {
          callback()
        }
      }
    }
  ],
  description: [
    { required: true, message: '请输入使用说明', trigger: 'blur' }
  ],
  perLimit: [
    { required: true, message: '请输入每人限领数量', trigger: 'blur' }
  ],
  scope: [
    { required: true, message: '请选择使用范围', trigger: 'change' }
  ],
  categoryIds: [
    {
      required: true,
      message: '请选择商品分类',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.scope === 'category' && (!value || value.length === 0)) {
          callback(new Error('请选择商品分类'))
        } else {
          callback()
        }
      }
    }
  ],
  products: [
    {
      required: true,
      message: '请选择商品',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.scope === 'product' && (!value || value.length === 0)) {
          callback(new Error('请选择商品'))
        } else {
          callback()
        }
      }
    }
  ],
  totalQuantity: [
    { required: true, message: '请输入发放总量', trigger: 'blur' }
  ],
  issueType: [
    { required: true, message: '请选择发放方式', trigger: 'change' }
  ],
  issueCondition: [
    {
      required: true,
      message: '请选择发放条件',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.issueType === 'auto' && !value) {
          callback(new Error('请选择发放条件'))
        } else {
          callback()
        }
      }
    }
  ],
  levelIds: [
    {
      required: true,
      message: '请选择会员等级',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (
          form.issueType === 'auto' &&
          form.issueCondition === 'level' &&
          (!value || value.length === 0)
        ) {
          callback(new Error('请选择会员等级'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 商品分类选项
const categoryOptions = ref([])

// 会员等级选项
const memberLevels = ref([])

// 商品选择对话框
const productDialog = reactive({
  visible: false,
  keyword: '',
  list: [],
  selected: [],
  page: {
    current: 1,
    size: 10,
    total: 0
  }
})

// 禁用日期
const disabledDate = (time) => {
  return dayjs(time).isBefore(dayjs(), 'day')
}

// 禁用时间
const disabledTime = (date, type) => {
  if (type === 'start') {
    const now = dayjs()
    if (dayjs(date).isSame(now, 'day')) {
      return {
        hours: () => Array.from({ length: now.hour() }, (_, i) => i),
        minutes: () => Array.from({ length: now.minute() }, (_, i) => i)
      }
    }
  }
  return {}
}

// 获取商品分类
const getCategories = async () => {
  try {
    const { data } = await getMerchantCategories()
    categoryOptions.value = data
  } catch (error) {
    console.error('获取商品分类失败:', error)
    ElMessage.error('获取商品分类失败')
  }
}

// 获取会员等级
const getMemberLevels = async () => {
  try {
    const { data } = await getMerchantMemberLevels()
    memberLevels.value = data
  } catch (error) {
    console.error('获取会员等级失败:', error)
    ElMessage.error('获取会员等级失败')
  }
}

// 选择商品
const handleSelectProducts = () => {
  productDialog.visible = true
  productDialog.keyword = ''
  productDialog.selected = []
  getProductList()
}

// 搜索商品
const handleSearchProducts = () => {
  productDialog.page.current = 1
  getProductList()
}

// 获取商品列表
const getProductList = async () => {
  try {
    const params = {
      page: productDialog.page.current,
      size: productDialog.page.size,
      keyword: productDialog.keyword
    }
    const { data } = await getMerchantProducts(params)
    productDialog.list = data.list
    productDialog.page.total = data.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

// 商品选择变化
const handleProductSelectionChange = (selection) => {
  productDialog.selected = selection
}

// 商品分页
const handleProductPageSizeChange = (val) => {
  productDialog.page.size = val
  getProductList()
}

const handleProductPageChange = (val) => {
  productDialog.page.current = val
  getProductList()
}

// 确认选择商品
const handleConfirmProducts = () => {
  const newProducts = productDialog.selected.map(item => ({
    id: item.id,
    name: item.name,
    price: item.price
  }))
  form.products = newProducts
  form.productIds = newProducts.map(item => item.id)
  productDialog.visible = false
}

// 删除商品
const handleRemoveProduct = (index) => {
  form.products.splice(index, 1)
  form.productIds = form.products.map(item => item.id)
}

// 获取优惠券详情
const getCouponDetail = async () => {
  try {
    const { data } = await getMerchantCouponDetail(route.params.id)
    Object.assign(form, {
      name: data.name,
      type: data.type,
      value: data.value,
      minAmount: data.minAmount,
      validityType: data.validityType,
      timeRange: data.validityType === 'fixed' ? [data.startTime, data.endTime] : [],
      validDays: data.validDays,
      description: data.description,
      perLimit: data.perLimit,
      scope: data.scope,
      categoryIds: data.categoryIds || [],
      productIds: data.productIds || [],
      products: data.products || [],
      totalQuantity: data.totalQuantity,
      issueType: data.issueType,
      issueCondition: data.issueCondition,
      levelIds: data.levelIds || []
    })
  } catch (error) {
    console.error('获取优惠券详情失败:', error)
    ElMessage.error('获取优惠券详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    const params = { ...form }
    if (form.validityType === 'fixed') {
      const [startTime, endTime] = form.timeRange
      params.startTime = startTime
      params.endTime = endTime
    }
    delete params.timeRange

    if (isEdit.value) {
      await updateMerchantCoupon(route.params.id, params)
      ElMessage.success('更新成功')
    } else {
      await createMerchantCoupon(params)
      ElMessage.success('创建成功')
    }
    router.push('/merchant/marketing/coupon')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存优惠券失败:', error)
      ElMessage.error('保存优惠券失败')
    }
  }
}

// 取消
const handleCancel = () => {
  router.back()
}

onMounted(() => {
  getCategories()
  getMemberLevels()
  if (isEdit.value) {
    getCouponDetail()
  }
})
</script>

<style lang="scss" scoped>
.coupon-edit {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .coupon-form {
    max-width: 800px;
    margin: 0 auto;
  }

  .product-selection {
    .el-table {
      margin-top: 20px;
    }
  }

  .form-tip {
    margin-left: 10px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  .product-dialog-content {
    .search-bar {
      margin-bottom: 20px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 